using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Reactive.Concurrency;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using AForge.Video;
using Damany.Cameras;
using DevExpress.ExpressApp;
using DevExpress.ExpressApp.Actions;
using DevExpress.ExpressApp.Editors;
using DevExpress.ExpressApp.Utils;
using DevExpress.ExpressApp.Win.Templates.ActionContainers;
using DevExpress.Persistent.Base;
using DevExpress.XtraEditors;
using TransLogger.Module.BusinessObjects;
using TransLogger.Module.Win.Editors;
using System.Reactive.Linq;

namespace TransLogger.Module.Win.Controllers
{
    public partial class PhotoRotatorViewController : ViewController
    {
        private ViewItem _photoItem;

        public PhotoRotatorViewController()
        {
            InitializeComponent();
            RegisterActions(components);

            TargetObjectType = typeof(BusinessObjects.Driver);
            TargetViewType = ViewType.DetailView;

        }

        protected override void OnDeactivated()
        {
            base.OnDeactivated();

            //var editors = ((DetailView)View).GetItems<Editors.PhotoCaptureViewItem>();
            //foreach (var photoCaptureViewItem in editors)
            //{
            //    var c = ((Editors.PhotoCapturerControl)photoCaptureViewItem.Control);
            //    c.simpleButton1.Click += SimpleButton1OnClick;
            //}
            if (_imageObserver != null)
            {
                _imageObserver.Dispose();
            }

            var disposable = _source as IDisposable;
            if (disposable != null)
            {
                disposable.Dispose();
            }

            if (_source != null)
            {
                _source.SignalToStop();
            }
        }


        protected override void OnActivated()
        {
            base.OnActivated();
            var detailView = View as DetailView;
            _photoItem = detailView.FindItem("Photo");
            var button = detailView.FindItem("CaptureDriverPhoto");
            button.ControlCreated += ButtonOnControlCreated;

        }

        private void ButtonOnControlCreated(object sender, EventArgs eventArgs)
        {
            ((ButtonsContainer)((ViewItem)sender).Control).ActionItemAdding += OnActionItemAdding;
        }

        private void OnActionItemAdding(object sender, ActionItemEventArgs actionItemEventArgs)
        {
            if (actionItemEventArgs.Item.Action.Id == "CapturePhoto")
            {
                var button = actionItemEventArgs.Item.Control as SimpleButton;
                if (button != null)
                {
                    var imgList = new ImageList();
                    imgList.ImageSize = new Size(16, 16);
                    imgList.Images.Add(ImageLoader.Instance.GetImageInfo("Action_Debug_Start").Image);
                    imgList.Images.Add(ImageLoader.Instance.GetImageInfo("Action_Debug_Stop").Image);
                    button.ImageList = imgList;
                    button.Text = string.Empty;
                    button.ImageLocation = ImageLocation.MiddleCenter;
                    button.ImageIndex = 0;

                    button.Click += ButtonOnClick;
                }
            }
        }

        private void ButtonOnClick(object sender, EventArgs eventArgs)
        {
            var sb = ((SimpleButton)sender);
            sb.ImageIndex = sb.ImageIndex == 0 ? 1 : 0;
        }

        private bool _started = false;
        private IDisposable _imageObserver;
        private IVideoSource _source;

        private void simpleActionCaptureImage_Execute(object sender, SimpleActionExecuteEventArgs e)
        {
            if (_photoItem == null) return;

            if (!_started)
            {
                SetupImageSource();
                var observable = Observable.FromEventPattern<NewFrameEventArgs>(_source, "NewFrame");
                _imageObserver =
                    observable
                    .Select(ev => ev.EventArgs.Frame)
                    .ObserveOn(SynchronizationContext.Current)
                    .Subscribe(
                        img =>
                        {
                            if (_started)
                            {
                                var driver = ((DetailView)View).CurrentObject as Driver;
                                if (driver != null)
                                {
                                    driver.Photo = img;
                                }
                            }
                        });
                _started = true;
            }
            else
            {
                _started = false;
            }
        }

        private void SetupImageSource()
        {
            var settings = ObjectSpace.FindObject<BusinessObjects.Settings>(null);

            var source = new FoKoShVideoSourceAdapter(IntPtr.Zero);
            source.Camera.Ip = settings.PhotoCameraIp;
            source.Camera.Port = settings.PhotoCameraPort;
            source.Camera.UserName = settings.UserName;
            source.Camera.Password = settings.Password;
            source.FrameInterval = 2000;
            source.Start();
            _source = source;
        }

        protected override void OnViewControlsCreated()
        {
            base.OnViewControlsCreated();
            var button = (ActionContainerViewItem)((DetailView)View).FindItem("CaptureDriverPhoto");

        }
    }
}
